<?php
if (!defined('SMF'))
	die('Hacking attempt...');
	
global $smcFunc, $txt, $scripturl, $boarddir, $user_info;
global $dbtables, $color_line1, $color_line2, $color_header;
global $inventory_factor;
global $fighter_price, $torpedo_price;
global $colonist_price, $colonist_limit;
global $ore_price, $ore_delta, $ore_limit;
global $organics_price, $organics_delta, $organics_limit;
global $goods_price, $goods_delta, $goods_limit;
global $energy_price, $energy_delta, $energy_limit;
global $mine_hullsize;
global $debug;

require_once($boarddir . '/bnt/traderoute_funcs.php');

$engage = (int) $_GET['engage'];
$j = (int) $_GET['run'];

// Pull player info.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_ships}
	WHERE user_id = {int:user_id}
	LIMIT 1',
	array(
		'db_ships' => $dbtables['ships'],
		'user_id' => $user_info['id'],
	)
);
$playerinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_traderoutes}
	WHERE owner = {int:ship_id}',
	array(
		'db_traderoutes' => $dbtables['traderoutes'],
		'ship_id' => $playerinfo['ship_id']
	)
);
$num_traderoutes = $smcFunc['db_num_rows']($result);

$i = 0;

while($row = $smcFunc['db_fetch_assoc']($result))
{
	$traderoutes[$i] = $row; 
	$i++;
}
$smcFunc['db_free_result']($result);

$freeholds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];
$maxholds = NUM_HOLDS($playerinfo['hull']);
$maxenergy = NUM_ENERGY($playerinfo['power']);

// Run check for illegal values and log any results
if ($playerinfo['ship_colonists'] < 0 || $playerinfo['ship_ore'] < 0 || $playerinfo['ship_organics'] < 0 || $playerinfo['ship_goods'] < 0 || $playerinfo['ship_energy'] < 0 || $freeholds < 0)
{
    if ($playerinfo['ship_colonists'] < 0 || $playerinfo['ship_colonists'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_colonists]|colonists|$maxholds");
        $playerinfo['ship_colonists'] = 0;
    }
    if ($playerinfo['ship_ore'] < 0 || $playerinfo['ship_ore'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_ore]|ore|$maxholds");
        $playerinfo['ship_ore'] = 0;
    }
    if ($playerinfo['ship_organics'] < 0 || $playerinfo['ship_organics'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_organics]|organics|$maxholds");
        $playerinfo['ship_organics'] = 0;
    }
    if ($playerinfo['ship_goods'] < 0 || $playerinfo['ship_goods'] > $maxholds)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_goods]|goods|$maxholds");
        $playerinfo['ship_goods'] = 0;
    }
    if ($playerinfo['hip_energy'] < 0 || $playerinfo['ship_energy'] > $maxenergy)
    {
        adminlog(LOG_ADMIN_ILLEGVALUE, $playerinfo['ship_id'], "$playerinfo[ship_name]|$playerinfo[ship_energy]|energy|$maxenergy");
        $playerinfo['ship_energy'] = 0;
    }
    if ($freeholds < 0)
        $freeholds = 0;
	
	// Reset illegal values to 0.
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET ship_ore = {int:ship_ore},
			ship_organics = {int:ship_organics},
			ship_goods = {int:ship_goods},
			ship_energy = {int:ship_energy},
			ship_colonists = {int:ship_colonists},
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_ore' => $playerinfo['ship_ore'],
			'ship_organics' => $playerinfo['ship_organics'],
			'ship_goods' => $playerinfo['ship_goods'],
			'ship_energy' => $playerinfo['ship_energy'],
			'ship_colonists' => $playerinfo['ship_colonists'],
			'ship_id' => $playerinfo['ship_id']
		)
	);
}

// Run sanity checks.
foreach($traderoutes as $testroute)
{
	if ($testroute['traderoute_id'] == $engage)
		$traderoute = $testroute;
	
	if ($debug)
	{
		echo '<pre>';
		print_r($traderoute);
		echo '</pre>';
	}
}

if (!isset($traderoute))
{
	echo '<p>', $txt['bnt_tdr_engagenonexist'], '</p>';
	return;
}

if ($traderoute['owner'] != $playerinfo['ship_id'])
{
	echo '<p>', $txt['bnt_tdr_notowntdr'], '</p>';
	return;
}

// ********************************
// *****  Source Check ************
// ********************************

// Check if source is a port
if ($traderoute['source_type'] == 'P')
{
	// Retrieve source port info here, we'll need it later.
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_universe}
		WHERE sector_id = {int:source_id}',
		array(
			'db_universe' => $dbtables['universe'],
			'source_id' => $traderoute['source_id']
		)
	);
	if($smcFunc['db_num_rows']($result) == 0)
		traderoute_die($txt['bnt_tdr_invalidspoint']);

	$source = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	/* Players are now moved to the correct sector!
	
	if ($traderoute['source_id'] != $playerinfo['sector'])
	{
		$txt['bnt_tdr_inittdr'] = str_replace("[tdr_source_id]", $traderoute['source_id'], $txt['bnt_tdr_inittdr']);
		traderoute_die($txt['bnt_tdr_inittdr']);
	}
	*/
}
// Check if the source is a planet
elseif ($traderoute['source_type'] == 'L' || $traderoute['source_type'] == 'C')  
{
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_planets}
		WHERE planet_id = {int:source_id}',
		array(
			'db_planets' => $dbtables['planets'],
			'source_id' => $traderoute['source_id']
		)
	);
	if ($smcFunc['db_num_rows']($result) == 0)
		traderoute_die($txt['bnt_tdr_invalidsrc']);

	$source = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	/* Players are now moved to the correct sector!
	
	if ($source['sector_id'] != $playerinfo['sector'])
	{
		$txt['bnt_tdr_inittdrsector'] = str_replace("[tdr_source_sector_id]", $source['sector_id'], $txt['bnt_tdr_inittdrsector']);
		traderoute_die($txt['bnt_tdr_inittdrsector']);
	}
	*/
	
	if ($traderoute['source_type'] == 'L')
	{
		if ($source['owner'] != $playerinfo['ship_id'])
		{
			$txt['bnt_tdr_notyourplanet'] = str_replace("[tdr_source_name]", $source['name'], $txt['bnt_tdr_notyourplanet']);
			$txt['bnt_tdr_notyourplanet'] = str_replace("[tdr_source_sector_id]", $source['sector_id'], $txt['bnt_tdr_notyourplanet']);
			traderoute_die($txt['bnt_tdr_notyourplanet']);
		}
	}
	// Check to make sure player and planet are in the same corp.
	elseif ($traderoute['source_type'] == 'C')   
	{
		if ($source['corp'] != $playerinfo['team'])
		{
			$txt['bnt_tdr_notyourplanet'] = str_replace("[tdr_source_name]", $source['name'], $txt['bnt_tdr_notyourplanet']);
			$txt['bnt_tdr_notyourplanet'] = str_replace("[tdr_source_sector_id]", $source['sector_id'], $txt['bnt_tdr_notyourplanet']);
			$not_corp_planet = "$source[name] in $source[sector_id] not a Corporate Planet";
			traderoute_die($not_corp_planet);
		}
	}

	// Store source planet info, we'll need it later
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_universe}
		WHERE sector_id = {int:source_id}',
		array(
			'db_universe' => $dbtables['universe'],
			'source_id' => $source['source_id']
		)
	);
	if ($smcFunc['db_num_rows']($result) == 0)
		traderoute_die($txt['bnt_tdr_invalidssector']);

	$sourceport = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
}

// ********************************
// ***** Destination Check ********
// ********************************

//Check if destination is a port
if ($traderoute['dest_type'] == 'P')
{
	// Retrieve destination port info here, we'll need it later.
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_universe}
		WHERE sector_id = {int:dest_id}',
		array(
			'db_universe' => $dbtables['universe'],
			'dest_id' => $traderoute['dest_id']
		)
	);
	if ($smcFunc['db_num_rows']($result) == 0)
		traderoute_die($txt['bnt_tdr_invaliddport']);

	$dest = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
}
// Check if destination is a planet
elseif (($traderoute['dest_type'] == 'L') || ($traderoute['dest_type'] == 'C'))
{
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_planets}
		WHERE planet_id = {int:dest_id}',
		array(
			'db_planets' => $dbtables['planets'],
			'dest_id' => $traderoute['dest_id']
		)
	);
	if ($smcFunc['db_num_rows']($result) == 0)
		traderoute_die($txt['bnt_tdr_invaliddplanet']);

	$dest = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	// Store destination planet info, we'll need it later
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_universe}
		WHERE sector_id = {int:sector_id}',
		array(
			'db_universe' => $dbtables['universe'],
			'sector_id' => $dest['sector_id']
		)
	);
	if ($smcFunc['db_num_rows']($result) == 0)
		traderoute_die($txt['bnt_tdr_invaliddsector']);

	$destport = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
}

if (!isset($sourceport))
	$sourceport = $source;
if (!isset($destport))
	$destport = $dest;

// ***************************************************
// ***** Warp or RealSpace and generate distance *****
// ***************************************************
if ($traderoute['move_type'] == 'W')
{
	$result = $smcFunc['db_query']('', '
		SELECT link_id
		FROM {raw:db_links}
		WHERE link_start = {int:source}
		AND link_dest = {int:dest}',
		array(
			'db_links' => $dbtables['links'],
			'source' => $source['sector_id'],
			'dest' => $dest['sector_id']
		)
	);
	
	if ($smcFunc['db_num_rows']($result) == 0)
	{
		$txt['bnt_tdr_nowlink1'] = str_replace("[tdr_src_sector_id]", $source['sector_id'], $txt['bnt_tdr_nowlink1']);
		$txt['bnt_tdr_nowlink1'] = str_replace("[tdr_dest_sector_id]", $dest['sector_id'], $txt['bnt_tdr_nowlink1']);
		traderoute_die($txt['bnt_tdr_nowlink1']);
	}
	
	$smcFunc['db_free_result']($result);
	
	if ($traderoute['circuit'] == '2')
	{
		$result = $smcFunc['db_query']('', '
			SELECT link_id
			FROM {raw:db_links}
			WHERE link_start = {int:dest}
			AND link_dest = {int:source}',
			array(
				'db_links' => $dbtables['links'],
				'source' => $source['sector_id'],
				'dest' => $dest['sector_id']
			)
		);
		
		if ($smcFunc['db_num_rows']($result) == 0)
		{
			$txt['bnt_tdr_nowlink2'] = str_replace("[tdr_src_sector_id]", $source['sector_id'], $txt['bnt_tdr_nowlink2']);
			$txt['bnt_tdr_nowlink2'] = str_replace("[tdr_dest_sector_id]", $dest['sector_id'], $txt['bnt_tdr_nowlink2']);
			traderoute_die($txt['bnt_tdr_nowlink2']);
		}
		
		$dist['triptime'] = 4;
		$smcFunc['db_free_result']($result);
	}
	else
		$dist['triptime'] = 2;

	$dist['scooped'] = 0;
}
else
	$dist = traderoute_distance('P', 'P', $sourceport, $destport, $traderoute['circuit'], $playerinfo['trade_energy']);

if ($debug)
{
	echo '<pre>';
	print_r($dist);
	echo '</pre>';
}

// ********************************************
// ***** Check if player has enough turns *****
// ********************************************
if ($playerinfo['turns'] < $dist['triptime'])
{
	$txt['bnt_tdr_moreturnsneeded'] = str_replace("[tdr_dist_triptime]", $dist['triptime'], $txt['bnt_tdr_moreturnsneeded']);
	$txt['bnt_tdr_moreturnsneeded'] = str_replace("[tdr_playerinfo_turns]", $playerinfo['turns'], $txt['bnt_tdr_moreturnsneeded']);
	traderoute_die($txt['bnt_tdr_moreturnsneeded']);
}

// ********************************
// ***** Sector Defense Check *****
// ********************************
$hostile = 0;

// Check for defenses in the source sector that are not player owned.
$result = $smcFunc['db_query']('', '
	SELECT ship_id
	FROM {raw:db_sector_defence}
	WHERE sector_id = {int:source}
	AND ship_id <> {int:ship_id}',
	array(
		'db_sector_defence' => $dbtables['sector_defence'],
		'source' => $source['sector_id'],
		'ship_id' => $playerinfo['ship_id']
	)
);

/* If there are defeneses in the source sector not owned by the player,
check if they are on the same team. */
if ($smcFunc['db_num_rows']($result) > 0)
{
	$fighters_owner = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	$result = $smcFunc['db_query']('', '
		SELECT team
		FROM {raw:db_ships}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'source' => $source['sector_id'],
			'ship_id' => $fighters_owner['ship_id']
		)
	);
	$nsfighters = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	if ($nsfighters['team'] != $playerinfo['team'])
		$hostile = 1;
}

// Check for defenses in the destination sector that are not player owned.
$result = $smcFunc['db_query']('', '
	SELECT ship_id
	FROM {raw:db_sector_defence}
	WHERE sector_id = {int:dest}
	AND ship_id <> {int:ship_id}',
	array(
		'db_sector_defence' => $dbtables['sector_defence'],
		'dest' => $dest['sector_id'],
		'ship_id' => $playerinfo['ship_id']
	)
);

/* If there are defenses in the destination sector not owned by the player,
check if they are on the same team. */
if ($smcFunc['db_num_rows']($result) > 0)
{
	$fighters_owner = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	$result = $smcFunc['db_query']('', '
		SELECT team
		FROM {raw:db_ships}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $fighters_owner['ship_id']
		)
	);
	$nsfighters = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	if ($nsfighters['team'] != $playerinfo['team'])
		$hostile = 1;
}

if ($hostile > 0 && $playerinfo['hull'] > $mine_hullsize)
	traderoute_die($txt['bnt_tdr_tdrhostdef']);

// ***************************************
// ***** Special Port Nothing to do ******
// ***************************************
if ($traderoute['source_type'] == 'P' && $source['port_type'] == 'special' && $playerinfo['trade_colonists'] == 'N' && $playerinfo['trade_fighters'] == 'N' && $playerinfo['trade_torps'] == 'N')
	traderoute_die($txt['bnt_tdr_globalsetbuynothing']);


// *********************************************
// ***** Check if zone allows trading  SRC *****
// *********************************************
if ($traderoute['source_type'] == 'P')
{
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_zones}, {raw:db_universe}
		WHERE {raw:db_universe}.sector_id = {int:source_id}
		AND {raw:db_zones}.zone_id = {raw:db_universe}.zone_id',
		array(
			'db_zones' => $dbtables['zones'],
			'db_universe' => $dbtables['universe'],
			'source_id' => $traderoute['source_id']
		)
	);
	$zoneinfo = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	if ($zoneinfo['allow_trade'] == 'N')
		traderoute_die($txt['bnt_tdr_nosrcporttrade']);
	elseif ($zoneinfo['allow_trade'] == 'L')
	{
		if ($zoneinfo['corp_zone'] == 'N')
		{
			$result = $smcFunc['db_query']('', '
				SELECT team
				FROM {raw:db_zones}
				WHERE ship_id = {int:owner}',
				array(
					'db_ships' => $dbtables['ships'],
					'owner' => $zoneinfo['owner']
				)
			);
			$ownerinfo = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);

			if ($playerinfo['ship_id'] != $zoneinfo['owner'] && $playerinfo['team'] == 0 || $playerinfo['team'] != $ownerinfo['team'])
				traderoute_die($txt['bnt_tdr_tradesrcportoutsider']);
		}
		else
		{
			if ($playerinfo['team'] != $zoneinfo['owner'])
				traderoute_die($txt['bnt_tdr_tradesrcportoutsider']);
		}
	}
}

// **********************************************
// ***** Check if zone allows trading  DEST *****
// **********************************************
if ($traderoute['dest_type'] == 'P')
{
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_zones}, {raw:db_universe}
		WHERE {raw:db_universe}.sector_id = {int:dest_id}
		AND {raw:db_zones}.zone_id = {raw:db_universe}.zone_id',
		array(
			'db_zones' => $dbtables['zones'],
			'db_universe' => $dbtables['universe'],
			'dest_id' => $traderoute['dest_id']
		)
	);
	$zoneinfo = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	if( $zoneinfo['allow_trade'] == 'N')
		traderoute_die($txt['bnt_tdr_nodestporttrade']);
	elseif ($zoneinfo['allow_trade'] == 'L')
	{
		if ($zoneinfo['corp_zone'] == 'N')
		{
			$result = $smcFunc['db_query']('', '
				SELECT team
				FROM {raw:db_ships}
				WHERE ship_id = {int:owner}',
				array(
					'db_ships' => $dbtables['ships'],
					'owner' => $zoneinfo['owner']
				)
			);
			$ownerinfo = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);

			if ($playerinfo['ship_id'] != $zoneinfo['owner'] && $playerinfo['team'] == 0 || $playerinfo['team'] != $ownerinfo['team'])
				traderoute_die($txt['bnt_tdr_tradedestportoutsider']);
		}
		else
		{
			if ($playerinfo['team'] != $zoneinfo['owner'])
				traderoute_die($txt['bnt_tdr_tradedestportoutsider']);
		}
	}
}

//---------------------------------------------------
//--- Done with sanity checks ----------------
//---------------------------------------------------


/*	
	Make sure player is in the source sector,
	if not, move the player either warp or RS as determined
	by the route settings
*/
if ($playerinfo['sector'] != $traderoute['source_id'])
{
	$src_dist = traderoute_distance('P', 'P', $playerinfo['sector'], $traderoute['source_id'], 1, "N");
	
	// Check if player has enough turns
	if ($playerinfo['turns'] < $dist['triptime'])
	{
		$txt['bnt_tdr_moreturnsneeded'] = str_replace("[tdr_dist_triptime]", $dist['triptime'], $txt['bnt_tdr_moreturnsneeded']);
		$txt['bnt_tdr_moreturnsneeded'] = str_replace("[tdr_playerinfo_turns]", $playerinfo['turns'], $txt['bnt_tdr_moreturnsneeded']);
		traderoute_die($txt['bnt_tdr_moreturnsneeded']);
	}
	
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET turns = turns - {int:triptime}, 
			turns_used = turns_used + {int:triptime}, 
			ship_energy = ship_energy + {int:scooped},
			sector = {int:newsec}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'triptime' => intval($src_dist['triptime']),
			'newsec' => intval($traderoute['source_id']),
			'ship_id' => $playerinfo['ship_id'],
			'scooped' => $dist['scooped'],
		)
	);	
}

// Begin the actual trading.

$sourceresult = "";
$destresult = "";

$sourcecost = 0;

// $trade_stop will be set to true if a portfull status is encountered.
$tradestop = false;

//-------- Source is Port ------------
if ($traderoute['source_type'] == 'P')
{
	//-------- Special Port Section (begin) ------
	if ($source['port_type'] == 'special')
	{
		$total_credits = $playerinfo['credits'];

		if ($playerinfo['trade_colonists'] == 'Y')
		{
			$free_holds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];
			$colonists_buy = $free_holds;

			if ($playerinfo['credits'] < $colonist_price * $colonists_buy)
				$colonists_buy = round($playerinfo['credits'] / $colonist_price);

			if ($colonists_buy != 0)
				$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($colonists_buy) . ' ' . $txt['bnt_tdr_colonists'] . '<br>';

			$sourcecost -= $colonists_buy * $colonist_price;
			$total_credits -= $colonists_buy * $colonist_price;
		}
		else
			$colonists_buy = 0;

		if ($playerinfo['trade_fighters'] == 'Y')
		{
			$free_fighters = NUM_FIGHTERS($playerinfo['computer']) - $playerinfo['ship_fighters'];
			$fighters_buy = $free_fighters;

			if ($total_credits < $fighters_buy * $fighter_price)
			$fighters_buy = round($total_credits / $fighter_price);

			if ($fighters_buy != 0)
				$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($fighters_buy) . ' ' . $txt['bnt_tdr_fighters'] . '<br>';

			$sourcecost -= $fighters_buy * $fighter_price;
			$total_credits -= $fighters_buy * $fighter_price;
		}
		else
			$fighters_buy = 0;

		if ($playerinfo['trade_torps'] == 'Y')
		{
			$free_torps = NUM_TORPEDOES($playerinfo['torp_launchers']) - $playerinfo['torps'];
			
			$torps_buy = $free_torps;

			if ($total_credits < $torps_buy * $torpedo_price)
				$torps_buy = round($total_credits / $torpedo_price);

			if ($torps_buy != 0)
				$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($torps_buy) . ' ' . $txt['bnt_tdr_torps'] . '<br>';

			$sourcecost -= $torps_buy * $torpedo_price;
		}
		else
			$torps_buy = 0;

		if ($torps_buy == 0 && $colonists_buy == 0 && $fighters_buy == 0)
		{
			$sourceresult .= $txt['bnt_tdr_nothingtotrade'] . '<br>';
			$tradestop = "Nothing to trade!";
		}
		
		if ($traderoute['circuit'] == '1')
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_colonists = ship_colonists + {int:colonists_buy},
					ship_fighters = ship_fighters + {int:fighters_buy},
					torps = torps + {int:torps_buy},
					ship_energy = ship_energy + {int:scooped}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id'],
					'colonists_buy' => $colonists_buy,
					'fighters_buy' => $fighters_buy,
					'torps_buy' => $torps_buy,
					'scooped' => $dist['scooped']
				)
			);
		}
	}
	//-------- Special Port Section (end) ------

	//-------- Normal Port Section (begin) ------
	else
	{
		// Sell commodities
		// added below initializations, for traderoute bug - rjordan01

		$ore_buy = 0;
		$goods_buy = 0;
		$organics_buy = 0;
		$energy_buy = 0;
		$portfull = 0;
		
		if ($source['port_type'] != 'ore')
		{
			$ore_price1 = round($ore_price + $ore_delta * $source['port_ore'] / $ore_limit * $inventory_factor);
			if ($source['port_ore'] - $playerinfo['ship_ore'] <= 0)
			{
				$ore_buy = $source['port_ore'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$ore_buy = $playerinfo['ship_ore'];
				
			$sourcecost += $ore_buy * $ore_price1;
			
			if ($ore_buy != 0)
			{
				if ($portfull == 1)
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . '<br>';
			}
			$playerinfo['ship_ore'] -= $ore_buy;
		}

		$portfull = 0;
		if ($source['port_type'] != 'goods')
		{
			$goods_price1 = round($goods_price + $goods_delta * $source['port_goods'] / $goods_limit * $inventory_factor);
			if ($source['port_goods'] - $playerinfo['ship_goods'] <= 0)
			{
				$goods_buy = $source['port_goods'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$goods_buy = $playerinfo['ship_goods'];
			
			$sourcecost += $goods_buy * $goods_price1;
			if ($goods_buy != 0)
			{
				if ($portfull == 1)
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . '<br>';
			}
			$playerinfo['ship_goods'] -= $goods_buy;
		}

		$portfull = 0;
		if ($source['port_type'] != 'organics')
		{
			$organics_price1 = round($organics_price + $organics_delta * $source['port_organics'] / $organics_limit * $inventory_factor);
			if ($source['port_organics'] - $playerinfo['ship_organics'] <= 0)
			{
				$organics_buy = $source['port_organics'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$organics_buy = $playerinfo['ship_organics'];
				
			$sourcecost += $organics_buy * $organics_price1;
			if ($organics_buy != 0)
			{
				if ($portfull == 1)
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . '<br>';
			}
			$playerinfo['ship_organics'] -= $organics_buy;
		}

		$portfull = 0;
		if ($source['port_type'] != 'energy' && $playerinfo['trade_energy'] == 'Y')
		{
			$energy_price1 = round($energy_price + $energy_delta * $source['port_energy'] / $energy_limit * $inventory_factor);
			if ($source['port_energy'] - $playerinfo['ship_energy'] <= 0)
			{
				$energy_buy = $source['port_energy'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$energy_buy = $playerinfo['ship_energy'];
				
			$sourcecost += $energy_buy * $energy_price1;
			if ($energy_buy != 0)
			{
				if ($portfull == 1)
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$sourceresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . '<br>';
			}
			$playerinfo['ship_energy'] -= $energy_buy;
		}

		$free_holds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];

		// Time to buy.
		if ($source['port_type'] == 'ore')
		{
			$ore_price1 = round($ore_price - $ore_delta * $source['port_ore'] / $ore_limit * $inventory_factor);
			$ore_buy = $free_holds;
			if ($playerinfo['credits'] + $sourcecost < $ore_buy * $ore_price1)
				$ore_buy = round(($playerinfo['credits'] + $sourcecost) / $ore_price1);
			if ($source['port_ore'] < $ore_buy)
			{
				$ore_buy = $source['port_ore'];
				if ($source['port_ore'] == 0)
				{
					$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
					$tradestop = "Port full!";
				}
			}
			if ($ore_buy != 0)
				$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . '<br>';
			$playerinfo['ship_ore'] += $ore_buy;
			$sourcecost -= $ore_buy * $ore_price1;
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $source['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}

		if ($source['port_type'] == 'goods')
		{
			$goods_price1 = round($goods_price - $goods_delta * $source['port_goods'] / $goods_limit * $inventory_factor);
			$goods_buy = $free_holds;
			if ($playerinfo['credits'] + $sourcecost < $goods_buy * $goods_price1)
				$goods_buy = round(($playerinfo['credits'] + $sourcecost) / $goods_price1);
			if ($source['port_goods'] < $goods_buy)
			{
				$goods_buy = $source['port_goods'];
				if ($source['port_goods'] == 0)
				{
					$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
					$tradestop = "Port full!";
				}
			}
			if ($goods_buy != 0)
				$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . '<br>';
			$playerinfo['ship_goods'] += $goods_buy;
			$sourcecost -= $goods_buy * $goods_price1;
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $source['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}

		if ($source['port_type'] == 'organics')
		{
			$organics_price1 = round($organics_price - $organics_delta * $source['port_organics'] / $organics_limit * $inventory_factor);
			$organics_buy = $free_holds;
			if ($playerinfo['credits'] + $sourcecost < $organics_buy * $organics_price1)
				$organics_buy = round(($playerinfo['credits'] + $sourcecost) / $organics_price1);
			if ($source['port_organics'] < $organics_buy)
			{
				$organics_buy = $source['port_organics'];
				if ($source['port_organics'] == 0)
				{
					$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
					$tradestop = "Port full!";
				}
			}
			if ($organics_buy != 0)
				$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['organics_tdr_goods'] . '<br>';
			$playerinfo['ship_organics'] += $organics_buy;
			$sourcecost -= $organics_buy * $organics_price1;
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $source['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}

		if ($source['port_type'] == 'energy')
		{
			$energy_price1 = round($energy_price - $energy_delta * $source['port_energy'] / $energy_limit * $inventory_factor);
			
			//How much more energy can the player hold/buy?
			$energy_buy = NUM_ENERGY($playerinfo['power']) - $playerinfo['ship_energy'] - $dist['scooped'];
			
			if ($playerinfo['credits'] + $sourcecost < $energy_buy * $energy_price1)
				$energy_buy = round(($playerinfo['credits'] + $sourcecost) / $energy_price1);
			if ($source['port_energy'] < $energy_buy)
			{
				$energy_buy = $source['port_energy'];
				if ($source['port_energy'] == 0)
				{
					$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
					$tradestop = "Port full!";
				}
			}
			if ($energy_buy != 0)
				$sourceresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . '<br>';
			$playerinfo['ship_energy'] += $energy_buy;
			$sourcecost -= $energy_buy * $energy_price1;
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $source['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}
  
		$playerinfo['ship_energy'] += $dist['scooped'];
		if ($playerinfo['ship_energy'] > NUM_ENERGY($playerinfo['power']))
			$playerinfo['ship_energy'] = NUM_ENERGY($playerinfo['power']);
	  
		if ($ore_buy == 0 && $goods_buy == 0 && $energy_buy == 0 && $organics_buy == 0)
			$sourceresult .= $txt['bnt_tdr_nothingtotrade'] . '<br>';

		if ($traderoute['circuit'] == '1')
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_ore = {int:ship_ore},
					ship_energy = {int:ship_energy},
					ship_goods = {int:ship_goods},
					ship_organics = {int:ship_organics}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_ore' => $playerinfo['ship_ore'],
					'ship_energy' => $playerinfo['ship_energy'],
					'ship_goods' => $playerinfo['ship_goods'],
					'ship_organics' => $playerinfo['ship_organics'],
					'ship_id' => $playerinfo['ship_id'],
				)
			);
		}
	}
}
//------------- Source is port (end) ---------

//------------- Source is planet (begin) -----
elseif (($traderoute['source_type'] == 'L') || ($traderoute['source_type'] == 'C'))
{
	$free_holds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];

	if ($traderoute['dest_type'] == 'P')
	{
		// Pick stuff up to sell at port.
		if (($playerinfo['ship_id'] == $source['owner']) || ($playerinfo['team'] == $source['corp']))
		{
			if ($source['goods'] > 0 && $free_holds > 0 && $dest['port_type'] != 'goods')
			{
				if ($source['goods'] > $free_holds)
					$goods_buy = $free_holds;
				else
					$goods_buy = $source['goods'];
					
				$free_holds -= $goods_buy;
				$playerinfo['ship_goods'] += $goods_buy;
				$sourceresult .= $txt['bnt_tdr_loaded'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . '<br>';
			}
			else
				$goods_buy = 0;

			if ($source['ore'] > 0 && $free_holds > 0 && $dest['port_type'] != 'ore')
			{
				if ($source['ore'] > $free_holds)
					$ore_buy = $free_holds;
				else
					$ore_buy = $source['ore'];
					
				$free_holds -= $ore_buy;
				$playerinfo['ship_ore'] += $ore_buy;
				$sourceresult .= $txt['bnt_tdr_loaded'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . '<br>';
			}
			else
				$ore_buy = 0;

			if ($source['organics'] > 0 && $free_holds > 0 && $dest['port_type'] != 'organics')
			{
				if ($source['organics'] > $free_holds)
					$organics_buy = $free_holds;
				else
					$organics_buy = $source['organics'];
				$free_holds -= $organics_buy;
				$playerinfo['ship_organics'] += $organics_buy;
				$sourceresult .= $txt['bnt_tdr_loaded'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . '<br>';
			}
			else
				$organics_buy = 0;

			if ($ore_buy == 0 && $goods_buy == 0 && $organics_buy == 0)
				$sourceresult .= $txt['bnt_tdr_nothingtoload'] . '<br>';

			if ($traderoute['circuit'] == '1')
			{	
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET ship_ore = {int:ship_ore},
						ship_goods = {int:ship_goods},
						ship_organics = {int:ship_organics}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'ship_ore' => $playerinfo['ship_ore'],
						'ship_goods' => $playerinfo['ship_goods'],
						'ship_organics' => $playerinfo['ship_organics'],
						'ship_id' => $playerinfo['ship_id'],
					)
				);
			}
		}
		//
		// DOUBLECHECK
		//
		//Buy from planet - not implemented yet
		else  
		{
		}
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_planets}
			SET ore = ore - {int:ore_buy},
				goods = goods - {int:goods_buy},
				organics = organics - {int:organics_buy}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_planets' => $dbtables['planets'],
				'ore_buy' => $ore_buy,
				'goods_buy' => $goods_buy,
				'organics_buy' => $organics_buy,
				'ship_id' => $playerinfo['ship_id'],
			)
		);
	}
	
	// ---------- destination is a planet, so load colonist and weapons
	elseif (($traderoute['dest_type'] == 'L') || ($traderoute['dest_type'] == 'C'))
	{
		if ($source['colonists'] > 0 && $free_holds > 0 && $playerinfo['trade_colonists'] == 'Y')
		{
			if ($source['colonists'] > $free_holds)
				$colonists_buy = $free_holds;
			else
				$colonists_buy = $source['colonists'];
			$free_holds -= $colonists_buy;
			$playerinfo['ship_colonists'] += $colonists_buy;
			$sourceresult .= $txt['bnt_tdr_loaded'] . ' ' . NUMBER($colonists_buy) . ' ' . $txt['bnt_tdr_colonists'] . '<br>';
		}
		else
			$colonists_buy = 0;

		$free_torps = NUM_TORPEDOES($playerinfo['torp_launchers']) - $playerinfo['torps'];
		if ($source['torps'] > 0 && $free_torps > 0 && $playerinfo['trade_torps'] == 'Y')
		{
			if ($source['torps'] > $free_torps)
				$torps_buy = $free_torps;
			else
				$torps_buy = $source['torps'];
			$free_torps -= $torps_buy;
			$playerinfo['torps'] += $torps_buy;
			$sourceresult .= $txt['bnt_tdr_loaded'] . ' ' . NUMBER($torps_buy) . ' ' . $txt['bnt_tdr_torps'] . '<br>';
		}
		else
			$torps_buy = 0;

		$free_fighters = NUM_FIGHTERS($playerinfo['computer']) - $playerinfo['ship_fighters'];
		if ($source['fighters'] > 0 && $free_fighters > 0 && $playerinfo['trade_fighters'] == 'Y')
		{
			if( $source['fighters'] > $free_fighters)
				$fighters_buy = $free_fighters;
			else
				$fighters_buy = $source['fighters'];
			$free_fighters -= $fighters_buy;
			$playerinfo['ship_fighters'] += $fighters_buy;
			$sourceresult .= $txt['bnt_tdr_loaded'] . ' ' . NUMBER($fighters_buy) . ' ' . $txt['bnt_tdr_fighters'] . '<br>';
		}
		else
			$fighters_buy = 0;

		if ($fighters_buy == 0 && $torps_buy == 0 && $colonists_buy == 0)
		{
			$sourceresult .= $txt['bnt_tdr_nothingtoload'] . '<br>';
			$tradestop = "Nothing to trade!";
		}

		if ($traderoute['circuit'] == '1')
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET torps = {int:torps},
					ship_fighters = {int:ship_fighters},
					ship_colonists = {int:ship_colonists}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'torps' => $playerinfo['torps'],
					'ship_fighters' => $playerinfo['ship_fighters'],
					'ship_colonists' => $playerinfo['ship_colonists'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
		}
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_planets}
			SET torps = torps - {int:torps_buy},
				fighters = fighters - {int:fighters_buy},
				colonists = colonist - {int:colonists_buy}
			WHERE planet_id = {int:planet_id}',
			array(
				'db_planets' => $dbtables['planets'],
				'torps' => $playerinfo['torps'],
				'ship_fighters' => $playerinfo['ship_fighters'],
				'ship_colonists' => $playerinfo['ship_colonists'],
				'planet_id' => $source['planet_id'],
			)
		);
	}
}

$sourceresult .= $txt['bnt_tdr_scooped'] . ' ' . NUMBER($dist['scooped']) . ' ' . $txt['bnt_tdr_energy'] . '<br>';

if ($traderoute['circuit'] == '2')
{
	$playerinfo['credits'] += $sourcecost;
	$destcost = 0;
	
	// Destination is a port
	if ($traderoute['dest_type'] == 'P')
	{
		// Added the below for traderoute bug. - rjordan01
		$ore_buy = 0;
		$goods_buy = 0;
		$organics_buy = 0;
		$energy_buy = 0;

		// Sell commodities, runs check to see what the port is buying and sell to the port.
		$portfull = 0;
		if ($dest['port_type'] != 'ore')
		{
			$ore_price1 = round($ore_price + $ore_delta * $dest['port_ore'] / $ore_limit * $inventory_factor);
			if ($dest['port_ore'] - $playerinfo['ship_ore'] < 0)
			{
				$ore_buy = $dest['port_ore'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$ore_buy = $playerinfo['ship_ore'];

			$destcost += $ore_buy * $ore_price1;
			if ($ore_buy != 0)
			{
				if ($portfull == 1)
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . '<br>';
			}
			$playerinfo['ship_ore'] -= $ore_buy;
		}

		$portfull = 0;
		if ($dest['port_type'] != 'goods')
		{
			$goods_price1 = round($goods_price + $goods_delta * $dest['port_goods'] / $goods_limit * $inventory_factor);
			if ($dest['port_goods'] - $playerinfo['ship_goods'] < 0)
			{
				$goods_buy = $dest['port_goods'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$goods_buy = $playerinfo['ship_goods'];
			$destcost += $goods_buy * $goods_price1;
			if($goods_buy != 0)
			{
				if ($portfull == 1)
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . '<br>';
			}
			$playerinfo['ship_goods'] -= $goods_buy;
		}

		$portfull = 0;
		if ($dest['port_type'] != 'organics')
		{
			$organics_price1 = round($organics_price + $organics_delta * $dest['port_organics'] / $organics_limit * $inventory_factor);
			if ($dest['port_organics'] - $playerinfo['ship_organics'] < 0)
			{
				$organics_buy = $dest['port_organics'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$organics_buy = $playerinfo['ship_organics'];
			$destcost += $organics_buy * $organics_price1;
			if ($organics_buy != 0)
			{
				if ($portfull == 1)
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . '<br>';
			}
			$playerinfo['ship_organics'] -= $organics_buy;
		}

		$portfull = 0;
		if ($dest['port_type'] != 'energy' && $playerinfo['trade_energy'] == 'Y')
		{
			$energy_price1 = round($energy_price + $energy_delta * $dest['port_energy'] / $energy_limit * $inventory_factor);
			
			// Check if the player is trying to sell more energy that is availabe at the port, if so
			// the player buys all the available energy.
			if ($dest['port_energy'] - $playerinfo['ship_energy'] < 0)
			{
				$energy_buy = $dest['port_energy'];
				$portfull = 1;
				$tradestop = "Port full!";
			}
			else
				$energy_buy = $playerinfo['ship_energy'];
			
			$destcost += $energy_buy * $energy_price1;
			
			if ($energy_buy != 0)
			{
				if ($portfull == 1)
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . ' (' . $txt['bnt_tdr_portisfull'] . ')<br>';
				else
					$destresult .= $txt['bnt_tdr_sold'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . '<br>';
			}
			$playerinfo['ship_energy'] -= $energy_buy;
		}
		else
			$energy_buy = 0;

		$free_holds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];

		// Time to buy.
		if ($dest['port_type'] == 'ore')
		{
			$ore_price1 = round($ore_price - $ore_delta * $dest['port_ore'] / $ore_limit * $inventory_factor);
			if ($traderoute['source_type'] == 'L')
				$ore_buy = 0;
			else
			{
				$ore_buy = $free_holds;
				if ($playerinfo['credits'] + $destcost < $ore_buy * $ore_price1)
					$ore_buy = round(($playerinfo['credits'] + $destcost) / $ore_price1);
				if ($dest['port_ore'] < $ore_buy)
				{
					$ore_buy = $dest['port_ore'];
					if ($dest['port_ore'] == 0)
					{
						$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
						$tradestop = "Port full!";
					}
				}
				if ($ore_buy != 0)
					$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($ore_buy) . ' ' . $txt['bnt_tdr_ore'] . '<br>';
				$playerinfo['ship_ore'] += $ore_buy;
				$destcost -= $ore_buy * $ore_price1;
			}
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $dest['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}

		if ($dest['port_type'] == 'goods')
		{
			$goods_price1 = round($goods_price - $goods_delta * $dest['port_goods'] / $goods_limit * $inventory_factor);
			if($traderoute['source_type'] == 'L')
				$goods_buy = 0;
			else
			{
				$goods_buy = $free_holds;
				if ($playerinfo['credits'] + $destcost < $goods_buy * $goods_price1)
					$goods_buy = round(($playerinfo['credits'] + $destcost) / $goods_price1);
				if ($dest['port_goods'] < $goods_buy)
				{
					$goods_buy = $dest['port_goods'];
					if ($dest['port_goods'] == 0)
					{
						$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
						$tradestop = "Port full!";
					}
				}
				if ($goods_buy != 0)
					$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($goods_buy) . ' ' . $txt['bnt_tdr_goods'] . '<br>';
				$playerinfo['ship_goods'] += $goods_buy;
				$destcost -= $goods_buy * $goods_price1;
			}
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $dest['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}

		if ($dest['port_type'] == 'organics')
		{
			$organics_price1 = round($organics_price - $organics_delta * $dest['port_organics'] / $organics_limit * $inventory_factor);
			if ($traderoute['source_type'] == 'L')
				$organics_buy = 0;
			else
			{
				$organics_buy = $free_holds;
				if ($playerinfo['credits'] + $destcost < $organics_buy * $organics_price1)
					$organics_buy = round(($playerinfo['credits'] + $destcost) / $organics_price1);
				if ($dest['port_organics'] < $organics_buy)
				{
					$organics_buy = $dest['port_organics'];
					if ($dest['port_organics'] == 0)
					{
						$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
						$tradestop = "Port full!";
					}
				}
				if ($organics_buy != 0)
					$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($organics_buy) . ' ' . $txt['bnt_tdr_organics'] . '<br>';
				$playerinfo['ship_organics'] += $organics_buy;
				$destcost -= $organics_buy * $organics_price1;
			}
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $dest['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}

		if ($dest['port_type'] == 'energy')
		{
			$energy_price1 = round($energy_price - $energy_delta * $dest['port_energy'] / $energy_limit * $inventory_factor);
			if ($traderoute['source_type'] == 'L')
				$energy_buy = 0;
			else
			{
				$energy_buy = NUM_ENERGY($playerinfo['power']) - $playerinfo['ship_energy'] - $dist['scooped'];
				if ($playerinfo['credits'] + $destcost < $energy_buy * $energy_price1)
					$energy_buy = round(($playerinfo['credits'] + $destcost) / $energy_price1);
				if ($dest['port_energy'] < $energy_buy)
				{
					$energy_buy = $dest['port_energy'];
					if ($dest['port_energy'] == 0)
					{
						$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . ' (' . $txt['bnt_tdr_portisempty'] . ')<br>';
						$tradestop = "Port full!";
					}
				}
				if($energy_buy != 0)
					$destresult .= $txt['bnt_tdr_bought'] . ' ' . NUMBER($energy_buy) . ' ' . $txt['bnt_tdr_energy'] . '<br>';
				$playerinfo['ship_energy'] += $energy_buy;
				$destcost -= $energy_buy * $energy_price1;
			}

			if ($ore_buy == 0 && $goods_buy == 0 && $energy_buy == 0 && $organics_buy == 0)
			{
				$destresult .= $txt['bnt_tdr_nothingtotrade'] . '<br>';
				$tradestop = "Port full!";
			}

			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:ore_buy},
					port_energy = port_energy - {int:energy_buy},
					port_goods = port_goods - {int:goods_buy},
					port_organics = port_organics - {int:organics_buy}
				WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $dest['sector_id'],
					'ore_buy' => $ore_buy,
					'energy_buy' => $energy_buy,
					'goods_buy' => $goods_buy,
					'organics_buy' => $organics_buy
				)
			);
		}

		$playerinfo['ship_energy'] += $dist['scooped'];
		if ($playerinfo['ship_energy'] > NUM_ENERGY($playerinfo['power']))
			$playerinfo['ship_energy'] = NUM_ENERGY($playerinfo['power']);
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET ship_ore = {int:ship_ore},
				ship_goods = {int:ship_goods},
				ship_organics = {int:ship_organics},
				ship_energy = {int:ship_energy}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_ore' => $playerinfo['ship_ore'],
				'ship_goods' => $playerinfo['ship_goods'],
				'ship_organics' => $playerinfo['ship_organics'],
				'ship_energy' => $playerinfo['ship_energy'],
				'ship_id' => $playerinfo['ship_id'],
			)
		);
	}
	else //dest is planet
	{
		if ($traderoute['source_type'] == 'L' || $traderoute['source_type'] == 'C')
		{
			$colonists_buy = 0;
			$fighters_buy = 0;
			$torps_buy = 0;
		}

		if ($playerinfo['trade_colonists'] == 'Y')
		{
			$colonists_buy += $playerinfo['ship_colonists'];
			$col_dump = $playerinfo['ship_colonists'];
			if ($dest['colonists'] + $colonists_buy >= $colonist_limit)
			{
				$exceeding = $dest['colonists'] + $colonists_buy - $colonist_limit;
				$col_dump = $exceeding;
				$setcol = 1;
				$colonists_buy -= $exceeding;
				if ($colonists_buy < 0)
					$colonists_buy = 0;
			}
		}
		else
			$col_dump = 0;

		if ($colonists_buy != 0)
		{
			if (isset($setcol) && $setcol == 1)
				$destresult .= $txt['bnt_tdr_dumped'] . ' ' . NUMBER($colonists_buy) . ' ' . $txt['bnt_tdr_colonists'] . ' (' . $txt['bnt_tdr_planetisovercrowded'] . ')<br>';
			else
				$destresult .= $txt['bnt_tdr_dumped'] . ' ' . NUMBER($colonists_buy) . ' ' . $txt['bnt_tdr_colonists'] . '<br>';
		}

		if ($playerinfo['trade_fighters'] == 'Y')
		{
			$fighters_buy += $playerinfo['ship_fighters'];
			$fight_dump = $playerinfo['ship_fighters'];
		}
		else
			$fight_dump = 0;

		if ($fighters_buy != 0)
			$destresult .= $txt['bnt_tdr_dumped'] . ' ' . NUMBER($fighters_buy) . ' ' . $txt['bnt_tdr_fighters'] . '<br>';

		if ($playerinfo['trade_torps'] == 'Y')
		{
			$torps_buy += $playerinfo['torps'];
			$torps_dump = $playerinfo['torps'];
		}
		else
			$torps_dump = 0;

		if ($torps_buy != 0)
			$destresult .= $txt['bnt_tdr_dumped'] . ' ' . NUMBER($torps_buy) . ' ' . $txt['bnt_tdr_torps'] . '<br>';

		if ($torps_buy == 0 && $fighters_buy == 0 && $colonists_buy == 0)
			$destresult .= $txt['bnt_tdr_nothingtodump'] . '<br>';

		if ($traderoute['source_type'] == 'L' || $traderoute['source_type'] == 'C')
		{
			if ($playerinfo['trade_colonists'] == 'Y')
			{
				if(isset($setcol) && $setcol != 1)
					$col_dump = 0;
			}
			else
				$col_dump = $playerinfo['ship_colonists'];

			if ($playerinfo['trade_fighters'] == 'Y')
				$fight_dump = 0;
			else
				$fight_dump = $playerinfo['ship_fighters'];

			if ($playerinfo['trade_torps'] == 'Y')
				$torps_dump = 0;
			else
				$torps_dump = $playerinfo['torps'];
		}
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_planets}
			SET torps = torps + {int:torps_buy},
				fighters = fighters + {int:fighters_buy},
				colonists = colonists + {int:colonists_buy}
			WHERE planet_id = {int:planet_id}',
			array(
				'db_planets' => $dbtables['planets'],
				'torps_buy' => $torps_buy,
				'fighters_buy' => $fighters_buy,
				'colonists_buy' => $colonists_buy,
				'planet_id' => $traderoute['dest_id'],
			)
		);

		if ($traderoute['source_type'] == 'L' || $traderoute['source_type'] == 'C')
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_colonists = {int:col_dump},
					ship_fighters = {int:fight_dump},
					torps = {int:torps_dump},
					ship_energy = ship_energy + {int:scooped}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'col_dump' => $col_dump,
					'fight_dump' => $fight_dump,
					'torps_dump' => $torps_dump,
					'scooped' => $dist['scooped'],
					'ship_id' => $playerinfo['ship_id'],
				)
			);
		}
		else
		{
			if (isset($setcol) && $setcol == 1)
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET ship_colonists = {int:col_dump},
						ship_fighters = ship_fighters - {int:fight_dump},
						torps = torps - {int:torps_dump},
						ship_energy = ship_energy + {int:scooped}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'col_dump' => $col_dump,
						'fight_dump' => $fight_dump,
						'torps_dump' => $torps_dump,
						'scooped' => $dist['scooped'],
						'ship_id' => $playerinfo['ship_id'],
					)
				);
			}
			else
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET ship_colonists = ship_colonists - {int:col_dump},
						ship_fighters = ship_fighters - {int:fight_dump},
						torps = torps - {int:torps_dump},
						ship_energy = ship_energy + {int:scooped}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'col_dump' => $col_dump,
						'fight_dump' => $fight_dump,
						'torps_dump' => $torps_dump,
						'scooped' => $dist['scooped'],
						'ship_id' => $playerinfo['ship_id'],
					)
				);
			}
		}
	}	
	
	$destresult .= $txt['bnt_tdr_scooped'] . ' ' . NUMBER($dist['scooped']) . ' ' . $txt['bnt_tdr_energy'] . '<br>';
}
else
{
	$destresult .= $txt['bnt_tdr_onlyonewaytdr'];
	$destcost = 0;
}

if ($sourcecost > 0)
	$sourceresult .= $txt['bnt_tdr_profit'] . ' : ' . NUMBER(abs($sourcecost));
else
	$sourceresult .= $txt['bnt_tdr_cost'] . ' : ' . NUMBER(abs($sourcecost));
	
if ($destcost > 0)
	$destresult .= $txt['bnt_tdr_profit'] . ' : ' . NUMBER(abs($destcost));
else
	$destresult .= $txt['bnt_tdr_cost'] . ' : ' . NUMBER(abs($destcost));

$total_profit = $sourcecost + $destcost;

if ($traderoute['circuit'] == '1')
	$newsec = $destport['sector_id'];
else
	$newsec = $sourceport['sector_id'];
	
$update = $smcFunc['db_query']('', '
	UPDATE {raw:db_ships}
	SET turns = turns - {int:triptime}, 
		credits = credits + {int:total_profit}, 
		turns_used = turns_used + {int:triptime}, 
		sector = {int:newsec}
	WHERE ship_id = {int:ship_id}',
	array(
		'db_ships' => $dbtables['ships'],
		'triptime' => intval($dist['triptime']),
		'total_profit' => intval($total_profit),
		'newsec' => intval($newsec),
		'ship_id' => $playerinfo['ship_id'],
	)
);	

// Refresh player info.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_ships}
	WHERE user_id = {int:user_id}',
	array(
		'db_ships' => $dbtables['ships'],
		'user_id' => $user_info['id'],
	)
);
$playerinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

echo '
						<input type="hidden" id="source_type" value="', $traderoute['source_type'], '" />
						<input type="hidden" id="source_sector" value="', $source['sector_id'], '" />
						<input type="hidden" id="source_scooped" value="', $dist['scooped'], '" />
						<input type="hidden" id="source_profit" value="', $sourcecost, '" />
						<input type="hidden" id="source_result" value="', $sourceresult, '" />
						<input type="hidden" id="dest_type" value="', $traderoute['dest_type'], '" />
						<input type="hidden" id="dest_sector" value="', $dest['sector_id'], '" />
						<input type="hidden" id="dest_scooped" value="', $dist['scooped'], '" />
						<input type="hidden" id="dest_profit" value="', $destcost, '" />
						<input type="hidden" id="dest_result" value="', $destresult, '" />
						<input type="hidden" id="single_run_profit" value="', $total_profit, '" />
						<input type="hidden" id="single_run_turns" value="', NUMBER($dist['triptime']), '" />
						<input type="hidden" id="playerinfo_ore" value="', NUMBER($playerinfo['ship_ore']), '" />
						<input type="hidden" id="playerinfo_organics" value="', NUMBER($playerinfo['ship_organics']), '" />
						<input type="hidden" id="playerinfo_goods" value="', NUMBER($playerinfo['ship_goods']), '" />
						<input type="hidden" id="playerinfo_energy" value="', NUMBER($playerinfo['ship_energy']), '" />
						<input type="hidden" id="playerinfo_colonists" value="', NUMBER($playerinfo['ship_colonists']), '" />
						<input type="hidden" id="playerinfo_fighters" value="', NUMBER($playerinfo['ship_fighters']), '" />
						<input type="hidden" id="playerinfo_torps" value="', NUMBER($playerinfo['torps']), '" />
						<input type="hidden" id="playerinfo_credits" value="', NUMBER($playerinfo['credits']), '" />
						<input type="hidden" id="playerinfo_turns" value="', NUMBER($playerinfo['turns']), '" />
						<input type="hidden" id="playerinfo_turns_used" value="', NUMBER($playerinfo['turns_used']), '" />';
	
if ($traderoute['circuit'] == 2)
{
	//$txt['bnt_tdr_engageagain'] = str_replace("[tdr_engage]", $engage, $txt['bnt_tdr_engageagain']);
	//if ($j == 1)
	//{
	//	echo $txt['bnt_tdr_engageagain'];
	//	traderoute_results_show_repeat($engage);
	//}
}

if ($tradestop <> false)
	echo '<input type="hidden" id="tradestop" value="', $tradestop,'" />';
?>